/* eslint-disable prefer-promise-reject-errors */
import {
  AlipayCircleOutlined,
  LockOutlined,
  MailOutlined,
  BuildOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import { Alert, Form, Tabs } from 'antd';
import React, { useState, useEffect } from 'react';
import ProForm, { ProFormCaptcha, ProFormCheckbox, ProFormText } from '@ant-design/pro-form';
import { useIntl, connect, FormattedMessage } from 'umi';
import type { Dispatch } from 'umi';
import type { StateType } from '@/models/login';
import type { LoginParamsType } from '@/services/login';
import type { ConnectState } from '@/models/connect';

import styles from './index.less';

export type LoginProps = {
  dispatch: Dispatch;
  userLogin: StateType;
  submitting?: boolean;
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC<LoginProps> = (props) => {
  const { userLogin = {}, submitting } = props;
  const [form] = Form.useForm();

  const { status, type: loginType } = userLogin;
  const [type, setType] = useState<string>('account');
  const [cap, setCap] = useState({ token: '', img: '' });
  const intl = useIntl();

  const handleSubmit = (values: LoginParamsType) => {
    const { dispatch } = props;
    if (type === 'account') {
      dispatch({
        type: 'login/login',
        payload: { ...values, code_token: cap.token },
      });
    } else {
      const regesParams = { ...values, code_token: cap.token, avatar: '' };
      console.log();
    }
  };

  // const initCap = () => {
  //   getCode()
  //   .then(res => {
  //     if (res.code == 200) {
  //       setCap(res.data)
  //     }
  //   })
  // }

  useEffect(() => {
    // initCap()
  }, []);

  return (
    <div className={styles.main}>
      <ProForm
        initialValues={{
          autoLogin: true,
          // user_id: Math.random().toString(32).substr(2,8).toUpperCase(),
        }}
        form={form}
        submitter={{
          render: (_, dom) => dom.pop(),
          submitButtonProps: {
            loading: submitting,
            size: 'large',
            style: {
              width: '100%',
            },
          },
        }}
        onFinish={(values) => {
          handleSubmit(values);
          return Promise.resolve();
        }}
      >
        <Tabs activeKey={type} onChange={setType}>
          <Tabs.TabPane
            key="account"
            tab={intl.formatMessage({
              id: 'pages.login.accountLogin.tab',
              defaultMessage: '账户密码登录',
            })}
          />
          {/* <Tabs.TabPane
            key="register"
            tab={intl.formatMessage({
              id: 'pages.login.phoneLogin.tab',
              defaultMessage: '账号注册',
            })}
          /> */}
        </Tabs>

        {status === 'error' && loginType === 'account' && !submitting && (
          <LoginMessage
            content={intl.formatMessage({
              id: 'pages.login.accountLogin.errorMessage',
              defaultMessage: '账户或密码错误（admin/ant.design)',
            })}
          />
        )}
        {type === 'account' && (
          <>
            <ProFormText
              name="user_id"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={styles.prefixIcon} />,
              }}
              placeholder={intl.formatMessage({
                id: 'pages.login.username.placeholder',
                defaultMessage: '用户名: admin or user',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.username.required"
                      defaultMessage="请输入用户名!"
                    />
                  ),
                },
              ]}
            />
            <ProFormText.Password
              name="user_pwd"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon} />,
              }}
              placeholder={intl.formatMessage({
                id: 'pages.login.password.placeholder',
                defaultMessage: '密码: ant.design',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.password.required"
                      defaultMessage="请输入密码！"
                    />
                  ),
                },
              ]}
            />
            <ProFormText
              // <BuildOutlined />
              fieldProps={{
                size: 'large',
                prefix: <BuildOutlined className={styles.prefixIcon} />,
                addonAfter: (
                  <img
                    style={{ height: '38px', width: '100px' }}
                    src={cap.img || `http://localhost:8000/static/logo.f0355d39.svg`}
                  />
                ),
              }}
              rules={[
                {
                  required: true,
                  message: '请输入验证码',
                },
              ]}
              name="code"
              placeholder={intl.formatMessage({
                id: 'pages.login.captcha.placeholder',
                defaultMessage: '验证码',
              })}
            />
          </>
        )}

        {status === 'error' && loginType === 'register' && !submitting && (
          <LoginMessage content="验证码错误" />
        )}
        {type === 'register' && (
          <>
            <ProFormText
              required
              fieldProps={{
                size: 'large',
                prefix: <MobileOutlined className={styles.prefixIcon} />,
              }}
              name="user_id"
              placeholder={'登录ID'}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.phoneNumber.required"
                      defaultMessage="登录ID"
                    />
                  ),
                },
              ]}
            />
            <ProFormText
              required
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={styles.prefixIcon} />,
              }}
              name="user_name"
              placeholder={'账号名称'}
              rules={[
                {
                  required: true,
                  message: '请输入账号名称',
                },
              ]}
            />
            <ProFormText
              required
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={styles.prefixIcon} />,
              }}
              name="shop_name"
              placeholder={'店铺名称'}
              rules={[
                {
                  required: true,
                  message: '请输入店铺名称',
                },
              ]}
            />
            <ProFormText.Password
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon} />,
              }}
              placeholder="请输入密码"
              rules={[
                {
                  required: true,
                  message: '请输入密码',
                },
                {
                  min: 8,
                  message: '密码长度至少8位！',
                },
              ]}
              name="user_pwd"
            />
            <ProFormText.Password
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon} />,
              }}
              placeholder="请再次输入密码"
              name="re_user_pwd"
              dependencies={['user_pwd']}
              rules={[
                {
                  required: true,
                  message: '请输入密码',
                },
                {
                  min: 8,
                  message: '密码长度至少8位！',
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('user_pwd') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject('两次输入的密码不同!');
                  },
                }),
              ]}
            />
            <ProFormText
              // <BuildOutlined />
              fieldProps={{
                size: 'large',
                prefix: <BuildOutlined className={styles.prefixIcon} />,
                addonAfter: (
                  <img
                    onClick={initCap}
                    style={{ height: '38px', width: '100px' }}
                    src={cap.img || `http://localhost:8000/static/logo.f0355d39.svg`}
                  />
                ),
              }}
              rules={[
                {
                  required: true,
                  message: '请输入验证码',
                },
              ]}
              name="code"
              placeholder={intl.formatMessage({
                id: 'pages.login.captcha.placeholder',
                defaultMessage: '验证码',
              })}
            />
          </>
        )}
      </ProForm>
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
